import { Button, Drawer, Form, Input, InputNumber, message, Radio, Select, Switch } from 'antd'
import React, { useEffect, useState } from 'react'
import { DATASOURCE_TYPE_LIST, ES_DATASOURCE_LIST, RULE_LIST } from '../constant'
import api from '../../../http/index'
import ConfigDiff from './configDiff'


const { Option } = Select
const { Item } = Form
const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
}

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
}

const EditDialog = (props) => {
  const { current = {}, isShow, oncloseFun, handleRefresh } = props
  const [messageApi, contextHolder] = message.useMessage()
  const [DataSource, $DataSource] = useState([])
  const [SQLDataSource, $SQLDataSource] = useState([])
  const [alarmPlatformList, $alarmPlatformList] = useState([])
  const [loading, $loading] = useState(false)
  const [isDrawOpen, $isDrawOpen] = useState(false)
  const [currentData, $currentData] = useState('')

  const handleCancel = () => {
    oncloseFun && oncloseFun()
  }

  const [form] = Form.useForm()

  useEffect(() => {
    if (!isShow) return
    if (!current || !current.uuid) {
      form.resetFields()
    } else {
      form.setFieldsValue(current)
    }
    initDataSource()
    initAlarmPlatform()
  }, [current, isShow, form])

  const initDataSource = async () => {
    // SQL
    const res = await api.DatasourceApi.getAll()
    if (res.code === 200) {
      $SQLDataSource(res.data)
    }
    if (Number(current?.datasourceType) === 1) {
      $DataSource(SQLDataSource)
    } else {
      $DataSource(ES_DATASOURCE_LIST)
    }
  }

  const initAlarmPlatform = async () => {
    const res = await api.AlarmPlatformApi.getAll()
    if (res.code === 200) {
      $alarmPlatformList(res.data)
    }
  }

  const handleDatasourceTypeChange = (value) => {
    if (Number(value) === 1) {
      $DataSource(SQLDataSource)
      return
    }
    $DataSource(ES_DATASOURCE_LIST)
  }

  const editConfig = () => {
    console.log( 'current',current);
    $currentData(current?.sqlContent)
    $isDrawOpen(true)
  }

  const onFinish = (values) => {
    doAddHandler(values)
  }

  const handleSqlContentSave = (value) => {
    form.setFieldsValue({ sqlContent: value })
  }

  // 编辑、新增规则
  const doAddHandler = (value) => {
    try {
      const params = { ...current, ...value }
      if (params.alarmPlatformUuids) {
        params.alarmPlatformUuid = params.alarmPlatformUuids.join(',')
      }
      $loading(true)
      const newApi = params.uuid ? api.RuleApi.update : api.RuleApi.add
      newApi(params)
        .then((data) => {
          if (data.code !== 200) {
            messageApi.error(data.message)
            return
          }
          messageApi.success(params.uuid ? '编辑成功' : '新增成功')
          handleCancel()
          handleRefresh()
        })
        .finally(() => {
          $loading(false)
        })
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <>
      <Drawer
        title="告警配置"
        placement="right"
        open={isShow}
        zIndex={100}
        width={800}
        footer={null}
        destroyOnClose={true}
        onClose={handleCancel}
      >
        <Form
          {...layout}
          initialValues={current}
          form={form}
          name="control-hooks"
          onFinish={onFinish}
        >
          <Item
            name="name"
            label="告警名称"
            rules={[
              {
                required: true,
                message: '请输入告警名称',
              },
            ]}
          >
            <Input placeholder="请输入告警名称" />
          </Item>

          <Item name="status" valuePropName="checked" label="状态">
            <Switch />
          </Item>

          <Item name="isTest" valuePropName="checked" label="是否测试">
            <Switch />
          </Item>
          <Item
            name="ruleType"
            label="规则类型"
            rules={[
              {
                required: true,
                message: '请选择规则类型',
              },
            ]}
          >
            <Select placeholder="选择告警类型" allowClear>
              {RULE_LIST.map((item, i) => (
                <Option value={item.value} key={i}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </Item>

          <Item
            name="datasourceType"
            label="数据源类型"
            rules={[
              {
                required: true,
                message: '请选择数据源类型',
              },
            ]}
          >
            <Select
              placeholder="选择数据源类型"
              allowClear
              onChange={handleDatasourceTypeChange}
            >
              {DATASOURCE_TYPE_LIST.map((item) => {
                return (
                  <Option key={item.key} value={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          </Item>

          <Item
            name="datasourceUuid"
            label="数据源"
            rules={[
              {
                required: true,
                message: '请选择数据源',
              },
            ]}
          >
            <Select placeholder="选择数据源" allowClear>
              {DataSource.map((item, i) => {
                return (
                  <Option key={item.uuid || i} value={item.uuid || item.value}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Item>

          <Item
            name="alarmPlatformUuids"
            label="告警群"
            rules={[
              {
                required: true,
                message: '请选择',
              },
            ]}
          >
            <Select placeholder="请选择" mode="multiple" allowClear>
              {alarmPlatformList.map((item) => {
                return (
                  <Option key={item.uuid} value={item.uuid}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Item>
          <Item
            name="sqlContent"
            label="告警规则"
            rules={[
              {
                required: true,
                message: '请输入告警规则',
              },
            ]}
          >
            {/* <Input.TextArea placeholder="请输入告警规则" /> */}
            <Button type="primary" onClick={editConfig}>
              点击编辑
            </Button>
          </Item>

          <Item
            name="timeValue"
            label="对应时间"
            initialValue={1}
            rules={[
              {
                required: true,
                message: '请输入对应时间',
              },
            ]}
          >
            <InputNumber min={0} max={100} style={{ width: '100%' }} />
          </Item>
          <Item
            name="timeUnit"
            label="时间单位"
            rules={[
              {
                required: true,
                message: '请选择时间单位',
              },
            ]}
          >
            <Select placeholder="选择时间单位" allowClear>
              <Option value={1 * 60 * 1000} key={1}>
                分钟
              </Option>
              <Option value={1 * 60 * 60 * 1000} key={2}>
                小时
              </Option>
              <Option value={24 * 1 * 60 * 60 * 1000} key={3}>
                天
              </Option>
              <Option value={7 * 24 * 1 * 60 * 60 * 1000} key={4}>
                周
              </Option>
            </Select>
          </Item>
          <Item
            name="alarmOutputType"
            label="告警输出格式"
            rules={[
              {
                required: true,
                message: '请选择告警输出格式',
              },
            ]}
          >
            {/*企业微信机器人通知*/}
            <Radio.Group>
              <Radio value={1} key={1} checked>
                失败比例
              </Radio>
              <Radio value={2} key={2}>
                失败数量
              </Radio>
              <Radio value={0} key={0}>
                默认输出
              </Radio>
            </Radio.Group>
          </Item>

          <Item
            name="alarmPlatform"
            label="告警方式"
            rules={[
              {
                required: true,
                message: '请选择告警方式',
              },
            ]}
          >
            {/*企业微信机器人通知*/}
            <Radio.Group>
              <Radio value={'0'} key={0}>
                企业微信机器人通知
              </Radio>
              <Radio value={'1'} key={1} disabled={true}>
                邮件通知（todo）
              </Radio>
            </Radio.Group>
          </Item>

          <Item {...tailLayout}>
            <Button htmlType="button" onClick={handleCancel}>
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              style={{ marginLeft: 15 }}
            >
              确定
            </Button>
          </Item>
        </Form>
      </Drawer>
      <ConfigDiff
        isDrawOpen={isDrawOpen}
        config={currentData}
        datasourceType={form.getFieldValue('datasourceType')}
        onSave={handleSqlContentSave}
        onClose={() => {
          $isDrawOpen(false)
          $currentData('')
        }}
      />
      {contextHolder}
    </>
  )
}

export default EditDialog
